package cn.tedu.blog.server.test;
import com.aliyun.oss.model.*;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
public class SelectObject {

        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        private static String endpoint = "oss-cn-chengdu.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        private static String accessKeyId = "LTAI5tBmNrz8XJxc5VY95bQj";
        private static String accessKeySecret = "ubrCNXAK9bH0xybISzMJ9ENRhoc2Cl";
        // 填写Bucket名称，例如examplebucket。
        private static String bucketName = "laochengdu";

        public static void main(String[] args) throws Exception {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 填写Object完整路径后，根据SELECT语句查询文件中的数据。Object完整路径中不能包含Bucket名称。
            // 填写CSV格式的Object完整路径。
//            selectCsvSample("exampledir/exampleobject.txt", ossClient);
            // 填写JSON格式的Object完整路径。
            selectJsonSample("exampledir/exampleobject.json", ossClient);
            ossClient.shutdown();
        }

        private static void selectCsvSample(String key, OSS ossClient) throws Exception {
            // 填写上传的内容。
            String content = "name,school,company,age\r\n" +
                    "Lora Francis,School A,Staples Inc,27\r\n" +
                    "Eleanor Little,School B,\"Conectiv, Inc\",43\r\n" +
                    "Rosie Hughes,School C,Western Gas Resources Inc,44\r\n" +
                    "Lawrence Ross,School D,MetLife Inc.,24";

            ossClient.putObject(bucketName, key, new ByteArrayInputStream(content.getBytes()));

            SelectObjectMetadata selectObjectMetadata = ossClient.createSelectObjectMetadata(
                    new CreateSelectObjectMetadataRequest(bucketName, key)
                            .withInputSerialization(
                                    new InputSerialization().withCsvInputFormat(
                                            // 填写内容中不同记录之间的分隔符，例如\r\n。
                                            new CSVFormat().withHeaderInfo(CSVFormat.Header.Use).withRecordDelimiter("\r\n"))));
            System.out.println(selectObjectMetadata.getCsvObjectMetadata().getTotalLines());
            System.out.println(selectObjectMetadata.getCsvObjectMetadata().getSplits());

            SelectObjectRequest selectObjectRequest =
                    new SelectObjectRequest(bucketName, key)
                            .withInputSerialization(
                                    new InputSerialization().withCsvInputFormat(
                                            new CSVFormat().withHeaderInfo(CSVFormat.Header.Use).withRecordDelimiter("\r\n")))
                            .withOutputSerialization(new OutputSerialization().withCsvOutputFormat(new CSVFormat()));

            selectObjectRequest.setExpression("select * from ossobject where _4 > 40");// 使用SELECT语句查询文件中的数据。
            OSSObject ossObject = ossClient.selectObject(selectObjectRequest);

            // 读取内容。
            BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
            while (true) {
                String line = reader.readLine();
                if (line == null) {
                    break;
                }
                System.out.println(line);
            }
            reader.close();

            ossClient.deleteObject(bucketName, key);
        }

        private static void selectJsonSample(String key, OSS ossClient) throws Exception {

            SelectObjectRequest selectObjectRequest =
                    new SelectObjectRequest(bucketName, key)
                            .withInputSerialization(new InputSerialization()
                                    .withCompressionType(CompressionType.NONE)
                                    .withJsonInputFormat(new JsonFormat().withJsonType(JsonType.LINES)))
                            .withOutputSerialization(new OutputSerialization()
                                    .withCrcEnabled(true)
                                    .withJsonOutputFormat(new JsonFormat()))
                            .withExpression("select * from ossobject "); // 使用SELECT语句查询文件中的数据。

            OSSObject ossObject = ossClient.selectObject(selectObjectRequest);

            // 读取内容。
            BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
            StringBuffer buffer = new StringBuffer();
            while (true) {
                String line = reader.readLine();
                buffer.append(line);
                if (line == null) {
                    break;
                }
                System.out.println("文本内容："+line);

            }
            reader.close();

            ossClient.deleteObject(bucketName, key);
        }

}
